<?php
/*
# $Id$
#
# Generate a ZIP file containing ALL files so that a replica site can be built
# if needs be.
# This will include all images uploaded via the CMS, but not database backups as
# these are done separately.
# It will NOT backup any files in the /backups directory.
*/

use Buan\Database;
use Buan\Config;

// Init
if(!defined('CRON')) {
	die("Cannot execute this script directly.");
}

// Only run every 24 hours
if(time()-$__lastRunTime<(24*60*60)) {
	return 0;
}

// Function recursively backup a given folder
function addFolderToZip($rootDir, $dir, $zipArchive){
	if(is_dir("{$rootDir}/{$dir}")) {
		if($dh = opendir("{$rootDir}/{$dir}")) {

			// Add the directory
			$zipArchive->addEmptyDir($dir);

			// Loop through all the files
			while(($file = readdir($dh))!==FALSE) {

				// If it's a folder, run the function again!
				if(!is_file("{$rootDir}/{$dir}/{$file}")){

					// Skip parent and root directories
					if($file!=="." && $file!==".." && $file!==".svn") {
						addFolderToZip($rootDir, "{$dir}/{$file}", $zipArchive);
					}
				}

				// Add file
				else {
					$zipArchive->addFile("{$rootDir}/{$dir}/{$file}", "{$dir}/{$file}");
				}
			}
		}
	}
}

// Start building the zip
$tgtFile = Config::get('app.dir.backups').'/site-'.date("dmY", time()).'.zip';
$zip = new ZipArchive();
if(($zip->open($tgtFile, ZIPARCHIVE::CREATE))===TRUE) {
	$root = dirname(dirname(__FILE__));
	addFolderToZip($root, 'buan', $zip);
	addFolderToZip($root, 'config', $zip);
	addFolderToZip($root, 'controllers', $zip);
	addFolderToZip($root, 'lib', $zip);
	addFolderToZip($root, 'models', $zip);
	addFolderToZip($root, 'project-resources', $zip);
	addFolderToZip($root, 'public_html', $zip);
	addFolderToZip($root, 'scheduled-jobs', $zip);
	addFolderToZip($root, 'views', $zip);
	$zip->close();
}
?>